package com.project.controller.upload;

import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.aliyun.oss.OSSClient;
import com.dtyunxi.util.DateUtil;
import com.project.common.Constants;
import com.project.util.GenerateCode;
import com.project.util.OSSUtil;

/**
 * 上传文件Controller
 * 
 * @author MarkLau
 *
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);


	private String[] imgs = { "jpg", "jpeg", "gif", "bmp", "png" };

	/**
	 * 文件上传
	 * 
	 * @param file
	 *            上传的文件流
	 * @param common
	 *            图片注释
	 * @return JsonBean
	 * @author saiily
	 */
	@RequestMapping(value = "file")
	@ResponseBody
	public String file(HttpServletRequest request) {
		String url = "";
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				if (iter.hasNext()) {
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
						if (ArrayUtils.contains(imgs, suffix.toLowerCase())) {	
							String key = "image/"+DateUtil.format(new Date())+"/"+System.currentTimeMillis()+GenerateCode.randomCode(4)+"."+suffix;
							OSSClient ossClient = OSSUtil.getOSSClient();
							ossClient.putObject(OSSUtil.IMAGE_BUCKETNAME, key, file.getInputStream());
							url+="/"+key;
						}
					}
					
					// 记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					System.out.println(finaltime - pre);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
		return url;
	}

}
